import { hasMcResMessage, mcMessage, mcpingServer, McSever } from '../../utils'
import jsonfile from 'jsonfile'
import { Message, Middleware } from 'mirai-js'
import { Bot as BotType } from 'mirai-js/dist/node/index'
import path from 'path'
import { textCommandFilter } from '../../middleware/textCommandFilter'
import appConfig from '../../config/app.config'

export default (bot: BotType) => {
  bot.on(
    'GroupMessage',
    new textCommandFilter('mc').done(async (data) => {
      const file = jsonfile.readFileSync('./src/config/get_mc/config.json')
      const currentGroupId: number = data.sender.group.id
      const CumcServer = data.text || 'default'
      let currentServe = null
      // 取出当前选择的ip
      if (file.servers[currentGroupId]) {
        file.servers[currentGroupId].servers.some((item) => {
          if (item.name === CumcServer) {
            currentServe = item
          }
        })
      }
      if (!currentServe) {
        console.error(`当前群聊${currentGroupId}未配置服务器信息或指定的服务器不存在${CumcServer}`)
        return
      }
      const res = (await mcpingServer(currentServe.host, currentServe.port).catch((err) => {
        console.log(err)
        bot.sendMessage({
          group: data.sender.group.id,
          message: new Message().addText(`服务器未开启或者ip地址填写错误`),
        })
        return false
      })) as McSever
      if (!res) return
      const hasRes = hasMcResMessage(res)
      bot.sendMessage({
        group: data.sender.group.id,
        message: new mcMessage({ ...hasRes, ...{ serviceOptenTime: currentServe.serviceOpenTime } }),
      })
    }),
  )
}
